import { reqGetCode, reqUserRegister, reqUserLogin, reqGetUserInfo, reqUserLogout } from '@/api';
import { setToken, getToken, removeToken } from '@/utils/token';

const state = {
    code: "",
    token: getToken(),
    userInfo: {},
}

const mutations = {
    GetCode(state, code){
        state.code = code;
    },
    UserLogin(state, token){
        state.token = token;
    },
    GetUserInfo(state, userInfo){
        state.userInfo = userInfo;
    },
    UserLogout(state){
        state.token = '',
        state.userInfo = {},
        removeToken()
    },
}

const actions = {
    // 获取验证码
    async getCode({commit}, phone){
        let result = await reqGetCode(phone);
        // console.log("getCode", result)
        if(result.code == 200){
            commit("GetCode", result.data)
            return "ok";
        }else{
            return Promise.reject(new Error("faile"))
        }
    },
    // 用户注册
    async userRegister({commit}, userData){
       let result = await reqUserRegister(userData);
    //    console.log("userRegister",result)
       if(result.code == 200){
        return "ok";
       }else{
        return Promise.reject(new Error("faile"))
       }
    },
    // 用户登录
    async userLogin({commit}, userData){
        let result = await reqUserLogin(userData);
        // console.log("userLogin", result)
        if(result.code == 200){
            // token服务器下发的唯一标识，令牌，vuex不是持久化仓库存储数据
            commit("UserLogin", result.data.token)
            // 持久化存储token(会话存储更为合适)
            setToken(result.data.token);
            return "ok";
        }else{
            return Promise.reject(new Error("faile"))
        }
    },
    // 添加了token校验获取用户信息
    async getUserInfo({commit}){
        let result = await reqGetUserInfo();
        // console.log("getUserInfo", result)
        if(result.code == 200){
            commit("GetUserInfo", result.data)
            return "ok";
        }else{
            return Promise.reject()
        }
    },
    // 用户退出登录
    async userLogout({commit}){
        let result = await reqUserLogout();
        console.log("userLogout", result)
        if(result.code == 200){
            commit("UserLogout");
            return "ok";
        }else{
            return Promise.reject(new Error("faile"))
        }
    },
}

const getters = {

}

export default({
    state,
    mutations,
    actions,
    getters,
})